// pages/mechDetail/mechDetail.js
var app = getApp();
var util=require("../../utils/util");
var home=require("../../api/home");
var group=require("../../api/group");

Page({
  /*页面的初始数据*/
  data: {
    info: '',
    id: '',
    info: '',
    navColor: '',
    title:'',
    back_type: 1,
    imageUrl: '',
    imageIcon: false,
    scroll_top: [],
    current_index: 0,
    nav_ke_index: 0,
    exp_id: null,
    ke_list:[],
    ad_list:[{img:'https://ossdev0.jiabala.com/xpjbcic3f6xMj',title:'素质教育淘课平台'},{img:'https://ossdev0.jiabala.com/ACJ6e5bN2ZeA2',title:'附近海量兴趣课源'},{img:'https://ossdev0.jiabala.com/tyJt3SibJwZhR',title:'高效便捷服务保障'}],
    // news_list: [],
    bar_text: ["正价课程","机构介绍","授课老师","设施/服务"],
    pref_text: ['立减券','满减券','礼品券','','平台券'],
    bar_index: 0,
    fix: false,
    com_data: [],
    show_com: 2,
    pop_show: true,
    show_address: false,
    pref_list: [],
    label_list: [],
    currentPage: 1,
    pageSize: 10,
    hasMoreDate: true,
    latitude: 22.80536,
    longitude: 113.29321,
    token: '',
    userinfo: '',
    show_none: false,
    show_name: false,
    teach_list: [],
    educations:['小学','初中','高中','专科','本科','硕士','博士']
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    var that = this,id=options.id?options.id:decodeURIComponent(options.scene);
    if(options.type){
      that.setData({back_type:options.type})
    }
    var sysInfo = wx.getSystemInfoSync(),pixelRate = sysInfo.windowWidth / 750;
    that.setData({top_height: (sysInfo.statusBarHeight+44)/pixelRate,id:id})
    wx.getStorage({
      key: 'city',
      success:function(res){
        var info=res.data;
        that.setData({latitude: info.lat,longitude: info.lng});
        //
        that.get_mech_detail(id);
        that.get_cour_list(id,0);
        that.get_teach_list(id);
      },
      fail:function(){
        //
        that.get_mech_detail(id);
        that.get_cour_list(id,0);
        that.get_teach_list(id);
      }
    })
    that.get_pref_list(id);
    // that.get_home_nav();
    var status=options.status?options.status:0,key=["未知","课程详情","拼团详情","附近机构","搜索","我的收藏","附近机构地图","我的订单","我的优惠券","每日领券","首页优惠券过期提示"]
    // 事件统计
    app.td_app_sdk.event({
      id: 'mechDetail',
      label: '机构详情',
      params: {
        key1: key[status]
      }
    })
  },
  // 轮播图
  swiper_change:function(e){
    this.setData({current_index: e.detail.current})
  },
  // 放大预览图片
  preview_img:function(e){
    var that=this,info=that.data.info;
    var src=e.currentTarget.dataset.src;
    wx.previewImage({
      current: src,
      urls: info.swipers
    })
  },
  // 机构名（气泡）
  touch_start:function(e){
    var that=this;
    that.setData({show_name:true})
    setTimeout(()=>{that.setData({show_name:false})},3000)
  },
  // 页面滚动
  page_scroll:function(e){
    var that = this,scroll_top = that.data.scroll_top,info=that.data.info,top_height = that.data.top_height,index=that.data.bar_index;
    var scroll = e.detail.scrollTop;
    // console.log(scroll)
    if(scroll >= 160){
      that.setData({
        navColor: '#ffffff',
        title: info.name,
        imageUrl: info.logoImg,
        imageIcon: info.isCertified==1?true:false,
      })
    }else{
      that.setData({
        navColor: '',
        title:'',
        imageUrl: '',
        imageIcon: false,
      })
    }
    if(scroll_top.length>0){
      if(scroll>=scroll_top[0].top-top_height){
        if(!that.data.fix){
          that.setData({fix: !that.data.fix})
        }
      }else{
        if(that.data.fix){
          that.setData({fix: !that.data.fix})
        }
      }
    }
    for (var i = 0; i < scroll_top.length; i++) {
      if ((i + 1) < scroll_top.length&&i>0) {
        if (scroll >= (scroll_top[i].top-100) && scroll < (scroll_top[i + 1].top)) {
          index=i
        }
      }
      if (scroll < scroll_top[0].top-60) {
        index=0
      }
    }
    that.setData({ bar_index: index })
  },
  // 导航
  scroll_page_to:function(e){
    var that=this,bar_index=that.data.bar_index;
    var index=e.currentTarget.dataset.index;
    if(bar_index!=index){
      that.setData({bar_index:index,toView:"item"+(index+2)})
    }
  },
  // 机构课程分类切换
  check_nav_item:function(e){
    var that=this,nav_ke_index=that.data.nav_ke_index,id=that.data.id;
    var index=e.currentTarget.dataset.index,num=e.currentTarget.dataset.num;
    if(nav_ke_index != index){
      that.setData({nav_ke_index:index,ke_list:[],show_none:false})
      if(index==-1){
        that.get_group_list(id);
      }else{
        that.get_cour_list(id,index);
      }
    }
    var key=["正价课程","体验课程","拼团课程"]
    // 事件统计
    app.td_app_sdk.event({
      id: 'mechDetailEvent',
      label: '机构详情',
      params: {
        key1: key[num]
      }
    })
  },
  // 弹窗
  open_courpop:function(e){
    var that = this,label_list=that.data.label_list;
    var num = e.currentTarget.dataset.num;
    that.setData({show_com:num,pop_show: !that.data.pop_show})
    if(num==1){
      that.setData({com_data:that.data.pref_list})
    }else{
      that.setData({com_data:label_list})
    }
  },
  close_pop:function(e){
    var that = this;
    var obj = e.detail.pop_show;
    that.setData({pop_show: obj})
  },
  // 老师
  nav_teach_detail:function(e){
    var uid=e.currentTarget.dataset.uid,oid=e.currentTarget.dataset.oid;
    wx.navigateTo({
      url: '../famousDetail/famousDetail?uid='+uid+'&oid='+oid+'&type=3',
    })
  },
  nav_all_tec:function(){
    var that=this,id=that.data.id;
    wx.navigateTo({
      url: '../mechAllteach/mechAllteach?id='+id,
    })
  },
  // 跳转
  nav_all_ke:function(e){
    var that=this,id=that.data.id,nav_ke_index=that.data.nav_ke_index;
    var index=e.currentTarget.dataset.index;
    var type=nav_ke_index==-1?2:1;
    wx.navigateTo({
      url: '../mechAllcour/mechAllcour?id='+id+'&type='+type+'&cid='+nav_ke_index+'&step='+index,
    })
  },
  nav_mechIntr:function(){
    wx.navigateTo({
      url: '../mechIntr/mechIntr',
    })
  },
  // 联系机构
  call_phone:function(){
    var that=this,info=that.data.info;
    wx.makePhoneCall({
      phoneNumber: info.serverPhone,
      success:function(){},
      fail:function(){}
    })
    // 事件统计
    app.td_app_sdk.event({
      id: 'mechDetailEvent',
      label: '机构详情',
      params: {
        key1: "电话联系"
      }
    })
  },
  // 领取优惠卷
  get_pref:function(e){
    var that=this,pref_list=that.data.pref_list,token=that.data.token;
    var index=e.detail.index;
    if(pref_list[index].isReceive!=1){
      if(token){
        //
        that.user_get_pref(index)
      }else{
        wx.navigateTo({
          url: '../login/login',
        })
        that.setData({pop_show: true,pref_list:[]})
      }
    }
  },
  return:function(){},
  // 触底
  scroll_bottom:function(e){
    var that=this,hasMoreData=that.data.hasMoreData,id=that.data.id;
    if(hasMoreData){
      that.get_pref_list(id);
    }else{
      util.page_show_toast('没有更多了',1500);
    }
  },
  // 收藏
  coll_mech:function(){
    var that=this,info=that.data.info,token=that.data.token;
    if(token){
      if(info.collectionId){
        // 取消
        that.cancel_call_mech(token)
      }else{
        that.user_call_mech(token)
      }
    }else{
      wx.navigateTo({
        url: '../login/login',
      })
    }
    // 事件统计
    app.td_app_sdk.event({
      id: 'mechDetailEvent',
      label: '机构详情',
      params: {
        key1: "收藏"
      }
    })
  },
  // 路线
  open_location:function(){
    var that=this,info=that.data.info;
    wx.openLocation({
      latitude: info.lat,
      longitude: info.lng,
      name: info.name,
      address: info.mech_address,
      success:function(res){
        console.log('---路线---')
      }
    })
    // 事件统计
    app.td_app_sdk.event({
      id: 'mechDetailEvent',
      label: '机构详情',
      params: {
        key1: "打开地图"
      }
    })
  },
  // 渲染完成
  onReady: function () {
    var that = this;
    this.dialog = this.selectComponent('#mechpop');
  },
  get_page_scroll:function(){
    var that=this
    var query = wx.createSelectorQuery();
    query.selectAll('.page_scroll').boundingClientRect(function (res) {
      // console.log(res)
      that.setData({scroll_top: res})
    }).exec()
  },
  // 分享
  onShareAppMessage:function(){
    // 事件统计
    app.td_app_sdk.event({
      id: 'mechDetailEvent',
      label: '机构详情',
      params: {
        key1: "分享"
      }
    })
    var that=this,info=that.data.info;
    return {
      title: info.name,
      path: '/pages/mechDetail/mechDetail?id='+info.id+'&type=2',
      imageUrl: info.swipers[0]
    }
  },
  onShareTimeline:function(){
    var that=this,info=that.data.info;
    return{
      title: info.name,
      query: 'id='+info.id+'&type=2',
      imageUrl: info.swipers[0]
    }
  },
  // 刷新
  onShow:function(){
    var that=this,token=that.data.token,id=that.data.id;
    var token_again=wx.getStorageSync('token'),userinfo=wx.getStorageSync('userinfo');
    if(!token&&token_again){
      that.setData({token: token_again,userinfo:userinfo})
    }
    if(app.globalData.login){
      that.get_mech_detail(id);
      that.get_pref_list(id);
      app.globalData.login=false;
    }
  },
  // 获取详情
  get_mech_detail:function(id){
    wx.showLoading({title: '加载中'})
    var that=this;
    var params={
      "businessId": id,
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    home.get_mech_detail(params).then(res=>{
      if(res.data.code==200){
        var info=res.data.data,arr=[];
        arr.push(info.logoImg);
        info.swipers=info.synopsisImg?info.synopsisImg.split(","):arr;
        info.score=info.score?info.score.toFixed(1):'5.0';
        info.space=info.distance>1000?(info.distance/1000).toFixed(2):info.distance;
        info.foundTime=info.foundTime?util.formatTime_year_else(new Date(info.foundTime)):'';
        info.province=info.province?info.province:'';
        info.city=info.city?info.city:'';
        info.region=info.region?info.region:'';
        info.town=info.town?info.town:'';
        info.detail=info.detail?info.detail:'';
        info.mech_address=info.detail?(info.detail.indexOf("省")>0?info.detail:info.province+info.city+info.region+info.town+info.detail):info.province+info.city+info.region+info.town+info.detail;
        info.collectionCount=info.collectionCount?info.collectionCount:0;
        var details=info.synopsis?info.synopsis:'';
        if(details){
          if(details.indexOf('img')>-1){
            details=details.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
          }
          if(details.indexOf('<style>')>-1){
            details=details.replace(/<style>[\s\S]*?<\/style>/ig,'')
          }
          if(details.indexOf('<script>')>-1){
            details=details.replace(/<script>[\s\S]*?<\/script>/ig,'')
          }
        }
        info.synopsis=details;
        that.setData({info: info,label_list:info.backstageLabels})
        var mech_details={logoImg:info.logoImg,name:info.name,isCertified:info.isCertified,foundTime:info.foundTime,categoryNames:info.categoryNames,synopsis:info.synopsis}
        wx.setStorageSync('mech_details', mech_details)
        //
        that.mech_browse(id);
      }
    })
  },
  // 获取优惠券
  get_pref_list:function(id){
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize,pref_text=that.data.pref_text;
    var params={
      "businessId": id,
      "currentPage": currentPage,
      "pageSize": pageSize
    }
    home.get_mech_pref_list(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        for(var i=0;i<list.length;i++){
          list[i].couponStartTime=util.formatTime_year(new Date(list[i].couponStartTime))
          list[i].couponEndTime=util.formatTime_year(new Date(list[i].couponEndTime))
          list[i].couponWayName=pref_text[list[i].couponWay]
        }
        var pref_list = that.data.pref_list;
        pref_list = util.extend(pref_list, list)
        if (list.length < pageSize) {
          that.setData({
            pref_list: pref_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            pref_list: pref_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
      }
    })
  },
  // 领取优惠券
  user_get_pref:function(index){
    wx.showLoading({title: ''})
    var that=this,pref_list=that.data.pref_list,userinfo=that.data.userinfo,token=that.data.token;
    var params={
      "couponId": pref_list[index].id,
    }
    home.get_pref(params,token).then(res=>{
      if(res.data.code==200){
        util.page_show_toast('领取成功',1500);
        pref_list[index].isReceive=1;
        that.setData({pref_list:pref_list,com_data:pref_list})
      }
    })
  },
  // 课程分类
  get_home_nav:function(){
    var that=this;
    var params={	"currentPage": 1,"pageSize": 20}
    home.get_home_nav(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          if((list[i].name).indexOf("体验")>-1){
            that.setData({exp_id:list[i].id})
          }
        }
      }
    })
  },
  // 获取机构课程列表
  get_cour_list:function(bid,cid){
    wx.showLoading({title: '加载中'})
    var that=this;
    var params={
      "currentPage": 1,
      "pageSize": 100,
      "status": 3,
      "businessId": bid,
      // "courseNatureId": cid,
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    home.get_cour_list(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].introducePictures=list[i].introducePictures?list[i].introducePictures.split(","):'';
          list[i].score=list[i].score?list[i].score.toFixed(1):'5.0';
          list[i].labelName=list[i].labelName?list[i].labelName.split(","):''
          list[i].courseNatureName=list[i].courseNatureName?list[i].courseNatureName.substr(0,2):''
          list[i].sellCount=list[i].sellCount?list[i].sellCount:0
        }
        that.setData({ke_list:list,len:res.data.data.total,show_none:list.length>0?false:true})
        setTimeout(function(){
          that.get_page_scroll();
        },500)
      }
    })
  },
   // 拼团课程列表
   get_group_list:function(id){
    wx.showLoading({title:"加载中"})
    var that=this;
    var params={
      "currentPage": 1,
      "pageSize": 100,
      "activityType": 1,
      "name": '',
      "status": 2,
      "delFlag": 0,
      "upDownShelves": 1,
      "businessId": id,
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    group.get_group_list(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].introducePictures=list[i].courseAvatar?list[i].courseAvatar.split(","):'';
          list[i].score=list[i].score?list[i].score.toFixed(1):'5.0';
          list[i].space=list[i].distance>1000?(list[i].distance/1000).toFixed(2):list[i].distance;
        }
        that.setData({ke_list:list,len:res.data.data.total,show_none:list.length>0?false:true})
        that.get_page_scroll();
      }
    })
  },
  // 收藏
  user_call_mech:function(token){
    var that=this,info=that.data.info,userinfo=that.data.userinfo;
    var params={
      "createTime": new Date().getTime(),
      "businessId": info.id,
      "createAccountId": userinfo.id
    }
    home.call_mech(params,token).then(res=>{
      if(res.data.code==200){
        info.collectionId=res.data.data.id;
        info.collectionCount +=1;
        that.setData({info:info})
        util.page_show_toast('收藏成功',1500);
      }
    })
  },
  // 取消收藏
  cancel_call_mech:function(token){
    var that=this,info=that.data.info;
    var params={"id": info.collectionId};
    home.cancel_call_mech(params,token).then(res=>{
      if(res.data.code==200){
        info.collectionId= null;
        info.collectionCount -=1;
        that.setData({info:info})
        util.page_show_toast('取消收藏成功',1500);
      }
    })
  },
  // 浏览
  mech_browse:function(id){
    var that=this;
    var params={
      "createTime": new Date().getTime(),
      "businessId": id
    }
    home.mech_browse(params).then(res=>{
      
    })
  },
  // 获取名师列表
  get_teach_list:function(id){
    wx.showLoading({title: '加载中'})
    var that=this,educations=that.data.educations;
    var params={
      "businessId": id,
      "currentPage": 1,
      "pageSize": 5,
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    home.get_teach_list(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.data;
        for(var i=0;i<list.length;i++){
          list[i].realName=list[i].realName?(list[i].realName.indexOf("老师")>-1?list[i].realName:list[i].realName+"老师"):'';
          list[i].yearCount=list[i].teachingTime?new Date().getFullYear()-new Date(list[i].teachingTime).getFullYear()+1:'';
          list[i].count=list[i].studentCount>10000?Math.ceil(list[i].studentCount/10000)+'万':list[i].studentCount;
          list[i].educaName=list[i].education?educations[Number(list[i].education)-1]:'';
          list[i].positiveRate=list[i].positiveRate?list[i].positiveRate*100+'%':'';
        }
        that.setData({teach_list:list})
      }
    })
  },
})